#include "CallStatus.h"

namespace qwtapi
{

CallStatus::CallStatus(HCALL hCall)
    : m_hCall(hCall), m_pCallStatus(NULL)
{
    Q_ASSERT(NULL != hCall);
}

CallStatus::~CallStatus()
{
    if (m_pCallStatus)
        free(m_pCallStatus);
}

LONG CallStatus::refresh()
{
    // Allocate a buffer for the call information
    DWORD dwSize = (m_pCallStatus) ? m_pCallStatus->dwTotalSize : sizeof (LINECALLSTATUS) + 1024;
    for (int i = 0; i < 10; i++)
    {   
        if (m_pCallStatus == NULL)
        {
            m_pCallStatus = (LPLINECALLSTATUS) calloc(1, dwSize);
            if (m_pCallStatus == NULL)
                return LINEERR_NOMEM;
        }

        // Mark the size we are sending.
        reinterpret_cast<LPVARSTRING>(m_pCallStatus)->dwTotalSize = dwSize;
        LONG errCode = lineGetCallStatus (m_hCall, m_pCallStatus);
        if (0 != errCode)
            return errCode;

        // If we allocated enough memory we clear the part not being used and return without error.
        if (m_pCallStatus->dwNeededSize <= dwSize)
        {
            // TODO: Maybe clear unused memory.
            return 0;
        }

        // The memory we allocated was too small, so we increase the size and retry.
        dwSize = m_pCallStatus->dwNeededSize;
        free(m_pCallStatus);
        m_pCallStatus = NULL;
    }  
    return LINEERR_NOMEM;
}

bool CallStatus::isValid() const
{
    return NULL != m_pCallStatus;
}

CallState::Constant CallStatus::getCallState() const
{
    return isValid() ? static_cast<CallState::Constant>(m_pCallStatus->dwCallState) : CallState::UNKNOWN;
}

}
